import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useStatisticsStore = defineStore('statistics', () => {
  // 状态
  const loading = ref(false)
  const dateRange = ref(['2023-01-01', '2023-12-31'])

  // 生死数据统计
  const lifeDeathStats = ref({
    totalDeaths: 0,
    totalBirths: 0,
    deathsByAge: [],
    deathsByCause: [],
    deathsByRegion: [],
    monthlyTrends: []
  })

  // 业力分析数据
  const karmaStats = ref({
    averageKarma: 0,
    karmaDistribution: [],
    goodVsBadRatio: { good: 0, bad: 0 },
    karmaByRegion: [],
    karmaByAge: []
  })

  // 轮回数据统计
  const reincarnationStats = ref({
    reincarnationSuccess: 0,
    sixRealmsDistribution: [],
    reincarnationByKarma: [],
    averageWaitTime: 0
  })

  // 审判数据统计
  const judgmentStats = ref({
    totalCases: 0,
    casesByVerdict: [],
    averageJudgmentTime: 0,
    judgePerformance: []
  })

  // 计算属性
  const totalSouls = computed(() => lifeDeathStats.value.totalDeaths + lifeDeathStats.value.totalBirths)
  const netGrowth = computed(() => lifeDeathStats.value.totalBirths - lifeDeathStats.value.totalDeaths)
  const karmaHealthIndex = computed(() => {
    const total = karmaStats.value.goodVsBadRatio.good + karmaStats.value.goodVsBadRatio.bad
    return total > 0 ? ((karmaStats.value.goodVsBadRatio.good / total) * 100).toFixed(1) : 0
  })

  // 获取生死统计数据
  const fetchLifeDeathStats = async () => {
    loading.value = true
    try {
      // 模拟API调用
      await new Promise((resolve) => setTimeout(resolve, 1000))

      lifeDeathStats.value = {
        totalDeaths: 8456,
        totalBirths: 9123,
        deathsByAge: [
          { ageGroup: '0-10', count: 234 },
          { ageGroup: '11-20', count: 156 },
          { ageGroup: '21-30', count: 456 },
          { ageGroup: '31-40', count: 789 },
          { ageGroup: '41-50', count: 1234 },
          { ageGroup: '51-60', count: 1876 },
          { ageGroup: '61-70', count: 2345 },
          { ageGroup: '71-80', count: 1876 },
          { ageGroup: '81-90', count: 1234 },
          { ageGroup: '90+', count: 256 }
        ],
        deathsByCause: [
          { cause: '自然死亡', count: 3456, percentage: 40.8 },
          { cause: '疾病', count: 2345, percentage: 27.7 },
          { cause: '意外事故', count: 1234, percentage: 14.6 },
          { cause: '自然灾害', count: 876, percentage: 10.4 },
          { cause: '其他', count: 545, percentage: 6.5 }
        ],
        deathsByRegion: [
          { region: '北京', count: 1234 },
          { region: '上海', count: 1123 },
          { region: '广州', count: 987 },
          { region: '深圳', count: 876 },
          { region: '其他', count: 4236 }
        ],
        monthlyTrends: [
          { month: '1月', deaths: 678, births: 745 },
          { month: '2月', deaths: 623, births: 689 },
          { month: '3月', deaths: 734, births: 812 },
          { month: '4月', deaths: 698, births: 756 },
          { month: '5月', deaths: 723, births: 789 },
          { month: '6月', deaths: 756, births: 823 },
          { month: '7月', deaths: 789, births: 856 },
          { month: '8月', deaths: 712, births: 778 },
          { month: '9月', deaths: 698, births: 745 },
          { month: '10月', deaths: 734, births: 789 },
          { month: '11月', deaths: 689, births: 734 },
          { month: '12月', deaths: 622, births: 607 }
        ]
      }
    } catch (error) {
      console.error('Failed to fetch life death stats:', error)
    } finally {
      loading.value = false
    }
  }

  // 获取业力统计数据
  const fetchKarmaStats = async () => {
    loading.value = true
    try {
      await new Promise((resolve) => setTimeout(resolve, 800))

      karmaStats.value = {
        averageKarma: 45.6,
        karmaDistribution: [
          { level: '圣贤', count: 123, percentage: 2.1 },
          { level: '善人', count: 1234, percentage: 21.3 },
          { level: '良民', count: 2345, percentage: 40.5 },
          { level: '平民', count: 1567, percentage: 27.1 },
          { level: '恶人', count: 456, percentage: 7.9 },
          { level: '罪民', count: 67, percentage: 1.1 },
          { level: '魔鬼', count: 8, percentage: 0.1 }
        ],
        goodVsBadRatio: { good: 4289, bad: 1511 },
        karmaByRegion: [
          { region: '北京', averageKarma: 67.8 },
          { region: '上海', averageKarma: 54.3 },
          { region: '广州', averageKarma: 43.2 },
          { region: '深圳', averageKarma: 38.7 },
          { region: '其他', averageKarma: 41.9 }
        ],
        karmaByAge: [
          { ageGroup: '18-30', averageKarma: 23.4 },
          { ageGroup: '31-45', averageKarma: 45.6 },
          { ageGroup: '46-60', averageKarma: 67.8 },
          { ageGroup: '61-75', averageKarma: 78.9 },
          { ageGroup: '76+', averageKarma: 89.1 }
        ]
      }
    } catch (error) {
      console.error('Failed to fetch karma stats:', error)
    } finally {
      loading.value = false
    }
  }

  // 获取轮回统计数据
  const fetchReincarnationStats = async () => {
    loading.value = true
    try {
      await new Promise((resolve) => setTimeout(resolve, 600))

      reincarnationStats.value = {
        reincarnationSuccess: 89.6,
        sixRealmsDistribution: [
          { realm: '天道', count: 234, percentage: 3.4 },
          { realm: '人道', count: 4567, percentage: 66.8 },
          { realm: '阿修罗道', count: 456, percentage: 6.7 },
          { realm: '畜生道', count: 1234, percentage: 18.1 },
          { realm: '饿鬼道', count: 234, percentage: 3.4 },
          { realm: '地狱道', count: 108, percentage: 1.6 }
        ],
        reincarnationByKarma: [
          { karmaRange: '200+', realm: '天道', probability: 95 },
          { karmaRange: '100-199', realm: '人道', probability: 90 },
          { karmaRange: '50-99', realm: '人道', probability: 75 },
          { karmaRange: '0-49', realm: '人道', probability: 60 },
          { karmaRange: '-1 to -49', realm: '畜生道', probability: 65 },
          { karmaRange: '-50 to -99', realm: '饿鬼道', probability: 70 },
          { karmaRange: '-100以下', realm: '地狱道', probability: 85 }
        ],
        averageWaitTime: 49 // 天数
      }
    } catch (error) {
      console.error('Failed to fetch reincarnation stats:', error)
    } finally {
      loading.value = false
    }
  }

  // 获取审判统计数据
  const fetchJudgmentStats = async () => {
    loading.value = true
    try {
      await new Promise((resolve) => setTimeout(resolve, 700))

      judgmentStats.value = {
        totalCases: 5678,
        casesByVerdict: [
          { verdict: '直接轮回', count: 3456, percentage: 60.9 },
          { verdict: '地狱受刑', count: 1234, percentage: 21.7 },
          { verdict: '功德抵罪', count: 567, percentage: 10.0 },
          { verdict: '特殊处理', count: 421, percentage: 7.4 }
        ],
        averageJudgmentTime: 2.3, // 小时
        judgePerformance: [
          { judge: '秦广王', cases: 678, efficiency: 95.6 },
          { judge: '楚江王', cases: 645, efficiency: 92.3 },
          { judge: '宋帝王', cases: 623, efficiency: 89.7 },
          { judge: '五官王', cases: 598, efficiency: 91.2 },
          { judge: '阎罗王', cases: 756, efficiency: 97.8 }
        ]
      }
    } catch (error) {
      console.error('Failed to fetch judgment stats:', error)
    } finally {
      loading.value = false
    }
  }

  // 获取所有统计数据
  const fetchAllStats = async () => {
    await Promise.all([fetchLifeDeathStats(), fetchKarmaStats(), fetchReincarnationStats(), fetchJudgmentStats()])
  }

  // 设置日期范围
  const setDateRange = (range) => {
    dateRange.value = range
  }

  // 导出统计报告
  const exportReport = async (type) => {
    try {
      // 这里可以实现导出逻辑
      return { success: true, message: '报告导出成功' }
    } catch (error) {
      return { success: false, error: error.message }
    }
  }

  return {
    // 状态
    loading,
    dateRange,
    lifeDeathStats,
    karmaStats,
    reincarnationStats,
    judgmentStats,

    // 计算属性
    totalSouls,
    netGrowth,
    karmaHealthIndex,

    // 方法
    fetchLifeDeathStats,
    fetchKarmaStats,
    fetchReincarnationStats,
    fetchJudgmentStats,
    fetchAllStats,
    setDateRange,
    exportReport
  }
})
